package data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;

public class User{
	public String username;
	public String nickname;
	public String password;
	public String email;
	public String mark;
	public String avatarUrl;
	public GeoPoint location;
	public String id;
	public int gender;
	
	public ArrayList<PassByItem> items;
	public User()
	{
		items = new ArrayList<PassByItem>();
	}
	
	public void addItem(PassByItem item)
	{
		PassByItem it = getItem(item.id);
		if(it != null)
		{
			int index = items.indexOf(it);
			it.user = this;
			items.set(index, item);
		}else
		{
			items.add(item);
			item.user = this;
			PassByItemComparator c = new PassByItemComparator();
			Collections.sort(items, c);
		}
	}
	
	public PassByItem getLatestItem()
	{
		if(items.size()>0)
		{
			return items.get(items.size()-1);
		}
		return null;
	}
	
	public PassByItem getItem(String id)
	{
		Iterator<PassByItem> its = items.iterator();
		while(its.hasNext())
		{
			PassByItem item = its.next();
			if(item.id == id)
			{
				return item;
			}
		}
		return null;
	}
	
	public static User decodeUser(JSONObject obj)
	{
		try {
			User user = new User();
			user.username = obj.getString("username");
			user.nickname = obj.getString("nickname");
			user.email = obj.getString("email");
			user.mark = obj.getString("mark");
			user.avatarUrl = obj.getString("avatar_url");
			String p = obj.getString("location");
			float lat1 = Float.parseFloat(p.split(",")[0]);
			float lon1 = Float.parseFloat(p.split(",")[1]);
			user.location = new GeoPoint((int)(lat1 * 1E6), (int)(lon1 * 1E6));
			user.id = obj.getString("id");
			user.gender = Integer.parseInt(obj.getString("gender"));
			return user;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}
}
